﻿using BW.WMS.WareHouseCheck.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using BW.WMS.WareHouseAllot;
using BW.WMS.WareHouseManage;
using BW.WMS.WareHouseStatistics.Page;
using Microsoft.EntityFrameworkCore;

namespace BW.WMS.WareHouseCheck
{
    /// <summary>
    /// 库存查询接口实现层
    /// </summary>
    public class StockInquiryService : ApplicationService, IStockInquiryService
    {
        private readonly IRepository<GoodsModel, Guid> _goodsRepository;
        private readonly IRepository<GoodsTypeModel, Guid> _goodsTypeRepository;
        private readonly IRepository<Warehouse, Guid> _warehouseRepository;
        private readonly IRepository<Zone, Guid> _zoneRepository;
        private readonly IRepository<Location, Guid> _locationRepository;
        private readonly IRepository<Inventory, Guid> _inventoryRepository;
        private readonly IRepository<Material, Guid> _materialRepository;

        public StockInquiryService(
            IRepository<GoodsModel, Guid> goodsRepository,
            IRepository<GoodsTypeModel, Guid> goodsTypeRepository,
            IRepository<Warehouse, Guid> warehouseRepository,
            IRepository<Zone, Guid> zoneRepository,
            IRepository<Location, Guid> locationRepository,
            IRepository<Inventory, Guid> inventoryRepository,
            IRepository<Material, Guid> materialRepository)
        {
            _goodsRepository = goodsRepository;
            _goodsTypeRepository = goodsTypeRepository;
            _warehouseRepository = warehouseRepository;
            _zoneRepository = zoneRepository;
            _locationRepository = locationRepository;
            _inventoryRepository = inventoryRepository;
            _materialRepository = materialRepository;
        }

        /// <summary>
        /// 库存查询分页显示列表
        /// </summary>
        /// <returns></returns>
        public async Task<WareHouseStatistics.Page.PagedResultDto<StockInquiryDTO>> GetStockInquiryPageList(PageStockInquiry page)
        {
            // 获取所有查询源
            var inventoryQueryable = await _inventoryRepository.GetQueryableAsync();
            var materialQueryable = await _materialRepository.GetQueryableAsync();
            var goodsQueryable = await _goodsRepository.GetQueryableAsync();
            var goodsTypeQueryable = await _goodsTypeRepository.GetQueryableAsync();
            var warehouseQueryable = await _warehouseRepository.GetQueryableAsync();
            var zoneQueryable = await _zoneRepository.GetQueryableAsync();
            
            // 1. 构建查询
            var query = from inv in inventoryQueryable
                        join material in materialQueryable
                            on inv.MaterialId equals material.Id
                        join goods in goodsQueryable
                            on material.Code equals goods.GoodsCode into goodsGroup
                        from goods in goodsGroup.DefaultIfEmpty()
                        join goodsType in goodsTypeQueryable
                            on goods.GoodsTypeId equals goodsType.Id into goodsTypeGroup
                        from goodsType in goodsTypeGroup.DefaultIfEmpty()
                        join warehouse in warehouseQueryable
                            on inv.WarehouseId equals warehouse.Id
                        join zone in zoneQueryable
                            on inv.ZoneId equals zone.Id
                        select new StockInquiryDTO
                        {
                            Id = inv.Id,
                            GoodsCode = goods.GoodsCode ?? material.Code,
                            GoodsName = goods.GoodsName ?? material.Name,
                            GoodsStatus = goods != null ? goods.GoodsStatus : true,
                            GoodsTypeId = goods != null ? goods.GoodsTypeId : Guid.Empty,
                            GoodsTypeName = goodsType != null ? goodsType.GoodsTypeName : string.Empty,
                            GoodsUnit = goods != null ? goods.GoodsUnit : material.Unit,
                            Name = warehouse.Name,
                            Name1 = zone.Name,
                            Inventory = (int)inv.Quantity,
                            SumPrice = goods != null ? goods.Inventory * goods.InventoryPrice : 0,
                            CreationTime = inv.CreationTime,
                            CreatorId = inv.CreatorId,
                            LastModificationTime = inv.LastModificationTime,
                            LastModifierId = inv.LastModifierId
                        };

            // 2. 应用过滤
            if (!string.IsNullOrWhiteSpace(page.GoodsCode))
            {
                query = query.Where(q => q.GoodsCode.Contains(page.GoodsCode));
            }

            if (!string.IsNullOrWhiteSpace(page.GoodsName))
            {
                query = query.Where(q => q.GoodsName.Contains(page.GoodsName));
            }

            if (!string.IsNullOrWhiteSpace(page.Name))
            {
                query = query.Where(q => q.Name.Contains(page.Name));
            }

            // 3. 计算总数
            var totalCount = await query.CountAsync();

            // 4. 应用分页
            var items = await query
                .OrderByDescending(q => q.CreationTime)
                .Skip((page.PageIndex - 1) * page.PageSize)
                .Take(page.PageSize)
                .ToListAsync();

            // 5. 返回分页结果
            return WareHouseStatistics.Page.PagedResultDto<StockInquiryDTO>.Create(items, totalCount, page.PageIndex, page.PageSize);
        }
    }
}
